package com.lovezy.platform.core.utils;

import com.lovezy.platform.core.cache.Cache;
import com.lovezy.platform.core.exception.RequestErrorException;
import com.lovezy.platform.core.spring.SpringContext;
import net.sf.cglib.beans.BeanCopier;
import org.jetbrains.annotations.NotNull;

/**
 * 对象工具类
 * Created by jin on 2017/11/5.
 */
public class ObjectUtil {

    private static final Cache copierPool = SpringContext.getContext().getBean("guavaCache",Cache.class);

    public static void copy(Object source, Object target) {
        BeanCopier copier = create(source.getClass(), target.getClass());
        copier.copy(source, target, null);
    }

    public static <V> V copyTo(Object source, V target) {
        copy(source, target);
        return target;
    }

    public static void nonNull(Object... o) {
        for (Object o1 : o) {
            if (o1 == null) {
                throw new RequestErrorException();
            }
        }
    }

    public static void nonNull(String message,Object... o) {
        for (Object o1 : o) {
            if (o1 == null) {
                throw new RequestErrorException(message);
            }
        }
    }

    public static boolean ifNull(Object... objects) {
        for (Object object : objects) {
            if (object == null) {
                return true;
            }
        }
        return false;
    }

    public static <T> T ifPresent(T t,@NotNull  T defaultValue) {
        return t == null ? defaultValue : t;
    }

    public static <T> boolean isIn(T target,T...  os){
        for (Object o : os) {
            if (target.equals(o)) {
                return true;
            }
        }
        return false;
    }

    public static boolean byteToBoolean(Byte value) {
        return value != null && value == (byte) 1;
    }

    private static BeanCopier create(Class source, Class target) {
        String key = "BEAN_COPIER_" + source.getName() + "," + target.getName();
        return copierPool.get(key, () -> BeanCopier.create(source, target, false));
    }

}
